package cs236369.webserver;

import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class JavaCompile {

	private final JavaCompiler compiler;
	private final StandardJavaFileManager manager;
	private String jrePath = null;

	public JavaCompile(String _jrePath) {
		this.jrePath = _jrePath;
		compiler = ToolProvider.getSystemJavaCompiler();
		if (compiler == null)
			throw new RuntimeException("compiler not found");
		manager = compiler.getStandardFileManager(null, null, null);
		if (manager == null)
			throw new RuntimeException("compiler returned null file namager");
	}

	public Class<?> compileAndLoad(String srcPath,String qualifiedClassName) throws ClassNotFoundException {
		Iterable<? extends JavaFileObject> units = manager
				.getJavaFileObjects(srcPath);
		Boolean status = compiler.getTask(null, manager, null,
				Arrays.asList(new String[] { "-d", "bin" }), null, units)
				.call();
		if (status == null || !status.booleanValue()) {
			Log.err("JavaCompile: Compilation failed. Status: "+status.toString()+ "  srcPath: "+srcPath+" qualifiedClass:  "+qualifiedClassName);
			return null;
		} else {
			Log.out("JavaCompile: Compilation successful");
		}
		return manager.getClassLoader(javax.tools.StandardLocation.CLASS_PATH).loadClass(qualifiedClassName);
	}

	@Override
	protected void finalize() throws Throwable {
		if (manager != null)
			manager.close();
		super.finalize();
	}
}
